const Koa = require('koa');
const app = new Koa();

const KoaRouter = require('koa-router');
const router = new KoaRouter();

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

const query = require('./utils/query');

const jwt = require('jsonwebtoken');

router.post('/zhuce', async (ctx) => {
    // 获取参数
    const { username, password } = ctx.request.body;
    // 非空验证
    if (!username || !password) {
        ctx.body = {
            code: 400,
            message: '缺少必须参数',
        };
        return;
    }
    // 不能重复注册
    let res = await query('select * from user where username = ?', [username]);
    if (res.length > 0) {
        ctx.body = {
            code: 403,
            message: '用户已注册，不允许重复注册',
        };
        return;
    }
    // 持久化到数据库中
    res = await query('insert into user (username, password) values (?, ?)', [
        username,
        password,
    ]);
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '注册失败',
        };
        return;
    }
    // 注册成功
    ctx.body = {
        code: 200,
        message: '注册成功',
    };
});

router.post('/denglu', async (ctx) => {
    // 获取参数
    const { username, password } = ctx.request.body;
    // 根据用户名，查询数据库，判断用户是否存在
    let res = await query('select * from user where username = ?', [username]);
    if (res.length === 0) {
        ctx.body = {
            code: 404,
            message: '用户不存在',
        };
        return;
    }
    // 获取用户
    const user = res[0];
    // 判断密码
    if (user.password !== password) {
        ctx.body = {
            code: 400,
            message: '密码不正确',
        };
        return;
    }
    // 判断用户信息都正确时，就生成一个该用户的唯一身份标识 token
    const token = jwt.sign({ id: user.id, username: user.username }, '123456', {
        expiresIn: '2h',
    });

    delete user.password;

    // 登录成功了，将生成的 token 返给前端
    ctx.body = {
        code: 200,
        data: {
            token,
            user,
        },
        message: '登录成功',
    };
});

router.put('/users/password', async (ctx) => {
    // 获取参数
    const { oldpassword, newpassword } = ctx.request.body;
    // 修改谁的密码
    const token = ctx.headers.token;
    if (!token) {
        ctx.body = {
            code: 401,
            message: '用户未登录，无法调用该接口',
        };
        return;
    }
    // 服务器通过解析前端传来的 token，才能知道调用该接口的用户是谁
    let user;
    try {
        user = jwt.verify(token, '123456');
    } catch (error) {
        if (error.name === 'JsonWebTokenError') {
            ctx.body = {
                code: 401,
                message: '无效的token',
            };
            return;
        }

        if (error.name === 'TokenExpiredError') {
            ctx.body = {
                code: 401,
                message: 'token已过期',
            };
            return;
        }
    }
    // 判断原密码是否正确
    let res = await query('select * from user where id = ?', [user.id]);
    const userFromDB = res[0];
    if (userFromDB.password !== oldpassword) {
        ctx.body = {
            code: 400,
            message: '原密码不正确',
        };
        return;
    }
    // 新密码不能和原密码相等
    if (oldpassword === newpassword) {
        ctx.body = {
            code: 400,
            message: '新密码不能和原密码相等',
        };
        return;
    }
    // 修改该 token 所代表的用户的密码
    res = await query('update user set password = ? where id = ?', [
        newpassword,
        user.id,
    ]);
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 500,
            message: '密码修改失败',
        };
        return;
    }
    // 修改成功
    ctx.body = {
        code: 200,
        message: '密码修改成功',
    };
});

app.use(router.routes(), router.allowedMethods());
app.listen(3000, () => {
    console.log('http://localhost:3000');
});
